import React, { useEffect, useState } from 'react';
import Thumbnail from './Thumnnail';
import loader from '@/assets/images/file-loader.gif';
import RemoveIcon from '@/assets/images/remove.svg';
import { uploadResume } from '@/apis/resume';
import { message } from 'antd';

/** 上传进度展示组件 */
const UploadShow: React.FC<{
  files: {
    File: File;
    id: number;
    folderId: string;
  }[];
  remove: (id: number) => void;
  reSeturl?: (url: string, name: string, resumeid: number) => void;
}> = ({ files, remove, reSeturl }) => {
  // 待上传文件id列表
  const [fileIdList, setFileIdList] = useState<number[]>([]);

  useEffect(() => {
    files.forEach((file) => {
      if (!fileIdList.includes(file.id)) {
        setFileIdList((prev) => [...prev, file.id]);
        const data = {
          file: file.File,
          folder_id: file.folderId,
        };
        uploadResume(data)
          .then((res) => {
            if (res.code === 200) {
              message.success(`上传${file.File.name}成功`);
            } else {
              message.error(`上传${file.File.name}失败`);
            }
            // 删除该待上传文件
            remove(file.id);
            if (reSeturl) {
              reSeturl(res.data.address, file.File.name, res.data.resume_id);
            }
          })
          .catch((error) => {
            message.error(`上传${file.File.name}失败`);
            console.log(error);
            remove(file.id);
          });
      }
    });
  }, [files]);

  return (
    <>
      {' '}
      {files.length > 0 && (
        <ul className="shadow-drop-3 !important; fixed bottom-5 right-10 z-50 flex size-full h-fit max-w-[480px] flex-col rounded-[20px] border bg-white p-5">
          <h4 className="h4 text-light-100">上传中...</h4>
          {files.map((fileItem, index) => {
            const file = fileItem.File;
            const extension = file.name.split('.').pop()?.toLowerCase() || '';

            return (
              <li
                key={`${file.name}-${index}`}
                className="shadow-drop-3 !important flex items-center justify-between gap-3 rounded-xl p-3"
              >
                <div className="flex items-center gap-3">
                  <Thumbnail extension={extension} />
                  <div className="shadow-drop-3 !important flex flex-col justify-between gap-1 rounded-xl p-3">
                    {file.name}
                    <img
                      src={loader}
                      className="align-start h-1 w-20"
                      alt="Loader"
                    />
                  </div>
                </div>
                <img
                  src={RemoveIcon}
                  width={24}
                  height={24}
                  alt="Remove"
                  //   onClick={(e) => handleRemoveFile(e, file.name)}
                />
              </li>
            );
          })}
        </ul>
      )}
    </>
  );
};

export default UploadShow;
